Skip to main content

第 10 章:建立 Terraform 模組

建立組態檔

建立 main.tf

  • 使用 module 區塊載入模組
  • 這次的 source 填入自製模組的相對路徑
  • 給一個獨一無二的 bucket_name
terraform configuration
provider "aws" {
region = "ap-northeast-1"
}

module "website_bucket" {
source = "./modules/static-s3-bucket"

bucket_name = "<YOUR BUCKET NAME>"

tags = {
Terraform = "true"
Environment = "dev"
}
}

 outputs.tf
output "website_bucket_arn" {
description = "ARN of the bucket"
value = module.website_bucket.arn
}

output "website_bucket_name" {
description = "Name (id) of the bucket"
value = module.website_bucket.name
}

output "website_endpoint" {
description = "Domain name of the bucket"
value = module.website_bucket.website_endpoint
}

tree folder
$ tree
.
├── main.tf
├── modules
│   └── static-s3-bucket
│   ├── README.md
│   ├── main.tf
│   ├── outputs.tf
│   └── variables.tf
├── outputs.tf
└── www
├── error.html
└── index.html

www 資料夾是我們另外準備要放到 s3 上測試用的網頁檔,你可以準備自己想要的檔案。

安裝自製模組

執行指令 terraform init 或 terraform get 安裝模組

terraform init
Initializing modules...
- website_bucket in modules/static-s3-bucket

Initializing the backend...

Initializing provider plugins...
- Finding latest version of hashicorp/aws...
- Using hashicorp/aws v3.7.0 from the shared cache directory
...

執行 apply

terraform apply
...

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

Outputs:

website_bucket_arn = arn:aws:s3:::terraform-practice-write-module
website_bucket_name = <YOUR BUCKET NAME>
website_endpoint = <YOUR BUCKET NAME>.s3-website-ap-northeast-1.amazonaws.com

上傳檔案

使用 aws cli 執行指令上傳檔案,把網頁檔上傳到剛剛建立好的儲存貯體 (bucket),可以用 terraform output website_bucket_name 指令找到儲存貯體名稱 (bucket name),再來組合 s3 cp 的指令

範例如下:

aws s3 cp www/ s3://$(terraform output website_bucket_name)/ --recursive

上傳成功後,就要打來網址來測試了

可以用 terraform output website_endpoint 指令找出網址。

網址大概會找這樣: https://<YOUR BUCKET NAME>.s3-us-west-2.amazonaws.com/index.html

打開網址,如果看到剛剛上傳的 index.html 就表示我們成功了!

刪除測試資料

測試結束了,我們要刪除測試資料。這次跟以往不太一樣,因為 s3 儲存貯體 (bucket) 要先清空才能刪掉。

terraform destroy
...

module.website_bucket.aws_s3_bucket.s3_bucket: Destroying... [id=terraform-practice-write-module]

Error: error deleting S3 Bucket (terraform-practice-write-module): BucketNotEmpty: The bucket you tried to delete is not empty
status code: 409, request id: XXXXXX, host id: 7eI2q66OaJxxxxxxxx

AWS 會給你一個 409 的錯誤!

所以我們要執行 aws s3 rm 刪掉檔案:

aws s3 rm s3://$(terraform output website_bucket_name)/ --recursive

再執行 terraform destroy 刪掉我們建立的基礎架構:

terraform destroy
module.website_bucket.aws_s3_bucket.s3_bucket: Destroying... [id=terraform-practice-write-module]
module.website_bucket.aws_s3_bucket.s3_bucket: Destruction complete after 1s

Destroy complete! Resources: 1 destroyed.